package com.example;


/**
 * @Author loubobooo
 * @Description #112. 路径总和
 * @Date 2022/2/28
 */
public class PathSum {

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public boolean hasPathSum(TreeNode root, int targetSum) {
        if (root == null) {
            return false;
        }
        return dfs(root, targetSum);
    }

    private boolean dfs(TreeNode node, int targetSum) {
        if (node == null) {
            return false;
        }
        // 根节点到叶子节点 的路径， 从根遍历至左右节点上，看这条路径上所有节点值相加等于目标和 targetSum
        if (node.left == null && node.right == null) {
            if (targetSum == node.val) {
                return true;
            }
        }
        return dfs(node.left, targetSum - node.val) ||
                dfs(node.right, targetSum - node.val);
    }

}
